package com.qilin.hscs.hm.mqtt.handler;

import com.qilin.hscs.hm.enums.ServiceFlushEnum;
import com.qilin.hscs.hm.mqtt.constant.HostNameConstant;
import com.qilin.hscs.hm.mqtt.service.impl.entrance.ServiceEntrance;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by 10188 on 2018/3/23.
 */

@Component
public class LogicHandleCentry implements Observer<String>,HostNameConstant {

    private static final Logger logger= LogManager.getLogger(LogicHandleCentry.class.getName());

    private String msg;

    private String topicVar;

    private Observable<String> toRepeaterObserver;

    private Observable<String> toServiceObservable;

    private Observer<String> service;

    @Autowired
    private ServiceEntrance entrance;

    @Autowired
    private InnerHostRepeater innerHostRepeater;

    @Autowired
    private OutterHostRepeater outterHostRepeater;

    private void handle(String s) throws ClassNotFoundException {
        try {
            String[] content = s.split("#");
            String hostName = content[0];
            topicVar = content[1];
            msg = content[2];
            logger.debug(hostName + " " + topicVar + " " + msg);
            if (hostName.equals(outterHostName)) {
                logger.info("【收到外部转发器转发的消息】={}",msg);
                flushToService();
            } else if (hostName.equals(serviceName)) {
                logger.info("【收到service返还的消息】={}",msg);
                String signal = String.valueOf(msg.charAt(msg.length() - 1));
                if (signal.equals(String.valueOf(ServiceFlushEnum.handle_by_gateway.getCode()))) {
                    //System.out.println("转发给网关");
                    msg=msg.substring(0,msg.length()-1);//将信号去除
                    logger.info("【来自service反馈回的消息，消息需交由网关处理】");
                     flush(innerHostRepeater);//数据交由内部转发器转发给网关
                } else if (signal.equals(String.valueOf(ServiceFlushEnum.not_handle_by_gateway.getCode()))) {
                    System.out.println("不需要转发给网关");
                    msg = msg.substring(0, msg.length() - 1);//去掉msg上的信号
                    flush(outterHostRepeater);  //发送给外部转发器 从而转发到外App
                    flush(innerHostRepeater);  //发送给内部转发器 从而转发到内App
                }
            } else if (hostName.equals(innerHostName)) {
                logger.info("【来自内部转发器转发的消息】={}",msg);
                flushToService();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private final void flush(Observer observer){
        toRepeaterObserver= Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                e.onNext(handlerName+"#"+topicVar+"#"+msg);
            }
        });
        toRepeaterObserver.subscribe(observer);
    }

    private final void flushToService() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        toServiceObservable= Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception {
                e.onNext(handlerName+"#"+topicVar+"#"+msg);
            }
        });
        toServiceObservable.subscribe(entrance);
    }

    @Override
    public void onSubscribe(Disposable disposable) {

    }

    @Override
    public void onNext(String s) {
        try {
            handle(s);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void onComplete() {

    }
}
